import { createRouter, createWebHistory } from 'vue-router'
import DictType from '@/views/dict/DictType.vue'
import DictData from '@/views/dict/DictData.vue'
import Login from '@/views/Login.vue'
import TokenUtils from '@/utils/token-utils.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/',
      redirect:'/login'
    },
    {
      path:'/login',
      name:'Login',
      component:Login
    },
    
    {
      path: '/dict/type',
      name: 'DictType',
      component: DictType,
      meta: { requiresAuth: true }
    },
    {
      path: '/dict/data',
      name: 'DictData',
      component: DictData,
      meta: { requiresAuth: true }
    }
    
  ]
})

router.beforeEach(async (to, from, next) => {
  const hasToken = await TokenUtils.hasValidToken()
  
  if (to.meta.requiresAuth && !hasToken) {
    next({ name: 'Login' })
  } else if (to.path === '/login' && hasToken) {
    next('/dict/type')
  } else {
    next()
  }
})

export default router